package com.woniuxy.movice.mq;

import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.concurrent.TimeUnit;

import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.messaging.handler.annotation.Headers;
import org.springframework.messaging.handler.annotation.Payload;
import org.springframework.stereotype.Component;

import com.rabbitmq.client.Channel;
import com.woniuxy.movice.entity.Orders;
import com.woniuxy.movice.entity.Rounds;
import com.woniuxy.movice.mapper.OrdersMapper;
import com.woniuxy.movice.service.RoundService;
import com.woniuxy.movice.util.ConvertUtil;


/*//**
 * 消费过期订单
 * @author lxq
 * @data 2019年9月14日上午11:35:09
 */
@Component
public class Consumer {
	@Autowired
	private OrdersMapper ordersMapper;
	@Autowired
	private RoundService roundService;
	@Autowired
	private RedisTemplate<Object, Object> redisTemplate;
	
	@RabbitListener(bindings=@QueueBinding(
			value=@Queue(value="consumer-order",durable="true"),
			exchange=@Exchange(name="order-exchange",durable="true",type="direct"),
			key="key1"
			)
	)
	@RabbitHandler
	public void consumerOrder(@Payload Orders order,@Headers Map<String,Object> header,Channel chanel) throws IOException{
		Orders dborder=ordersMapper.selectByPrimaryKey(order.getOid());
		Long deliveryTag=(Long) header.get(AmqpHeaders.DELIVERY_TAG);
		//订单状态不等于1，直接消费该消息
		if(!dborder.getOstate().equals(1)){
			chanel.basicAck(deliveryTag, false);
			return ;
		}else{
			//将订单取消
			dborder.setOstate(5);
			ordersMapper.updateByPrimaryKeySelective(dborder);
			String selectSets=dborder.getSelectedSets();
			Integer roundId=dborder.getCid();
			Rounds round=roundService.getSetsInfo(roundId);
			Integer[][] seats=ConvertUtil.convertStringTOArrays(round.getYtlayout());
			Integer[][] selectedSeats=ConvertUtil.convertStringTOArrays(selectSets);
			for(int i=0;i<selectedSeats.length;i++){
				seats[selectedSeats[i][0]][selectedSeats[i][1]]=0;
			}
			String updateSeats=ConvertUtil.convertObjectTOJSON(seats);
			round.setYtlayout(updateSeats);
			roundService.updateLayout(roundId,updateSeats);
			long destroyTime=round.getPend().getTime()-new Date().getTime();
			redisTemplate.opsForValue().set("Round"+round.getId(), round,destroyTime,TimeUnit.MILLISECONDS);
			chanel.basicAck(deliveryTag, false);
		}
		
	}
}
